package com.aote.expression.function;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import com.aote.util.StringHelper;
import com.browsesoft.Entity;

public class SubByGroupFunction extends MultiValueFunction {

	public Collection invoke(List params) {
		if (!(params.get(0) instanceof Collection)) {
			return null;
		}
		List result = new LinkedList();
		// 运算对象
		List first = (List) params.get(0);
		List second = (List) params.get(1);
		// 运算符号
		String symbol = (String) params.get(2);
		// 分组标记
		String groupField = (String) params.get(3);
		List groupFields = StringHelper.getStrings(groupField, ";");
		if (groupFields.size() == 1) {
			groupFields.add(groupField);
		}
		// 求和字段
		String sumField = (String) params.get(4);
		List sumFields = StringHelper.getStrings(sumField, ";");
		if (sumFields.size() == 1) {
			sumFields.add(sumField);
		}
		// 保存两组里都有的项
		List temp = new LinkedList();
		Iterator iter = first.iterator();
		while (iter.hasNext()) {
			Entity entity = (Entity) iter.next();
			// 分组名和它对应的值
			String groupfield = (String) entity.getAttributes().get(
					groupFields.get(0));
			String firstValue = (String) entity.getAttributes().get(
					sumFields.get(0));
			// 在第二组中找分项和名字相同的实体，并把值相加
			Iterator iterator = second.iterator();
			while (iterator.hasNext()) {
				Entity ent = (Entity) iterator.next();
				// 如果找到了，处理
				if (groupfield.equals((String) ent.getAttributes().get(
						groupFields.get(1)))) {
					String secondValue = (String) ent.getAttributes().get(
							sumFields.get(1));
					double sum = 0;
					// 判断是加还是减
					if (symbol.equals("+")) {
						sum = Double.parseDouble(firstValue)
								+ Double.parseDouble(secondValue);
					} else {
						sum = Double.parseDouble(firstValue)
								- Double.parseDouble(secondValue);
					}
					entity.getAttributes().put(sumFields.get(0),
							String.valueOf(sum));
					temp.add(ent);
					break;
				}
			}
			result.add(entity);
		}
		// 得到第二组中独有的项,逐个处理它的分组项和求和项的名字，以第一组的为主
		second.removeAll(temp);
		Iterator sen = second.iterator();
		while (sen.hasNext()) {
			Entity deal = (Entity) sen.next();
			String gvalue = (String) deal.getAttributes().get(
					groupFields.get(1));
			deal.getAttributes().remove(groupFields.get(1));
			deal.getAttributes().put(groupFields.get(0), gvalue);
			String svalue = (String) deal.getAttributes().get(sumFields.get(1));
			deal.getAttributes().remove(sumFields.get(1));
			deal.getAttributes().put(sumFields.get(0), svalue);
			result.add(deal);
		}
		return result;
	}
}
